package com.atguigu.flink.cep;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * Created by Smexy on 2023/3/4
 *
 *  时效性。定义当前模式匹配的下一条数据必须在规定的时间内到达。
 */
public class Demo9_Within
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((e, r) -> e.getTs());


        SingleOutputStreamOperator<WaterSensor> ds =
            env.readTextFile("data/cep.txt")
               .map(new WaterSensorMapFunction())
               .assignTimestampsAndWatermarks(watermarkStrategy);


        Pattern<WaterSensor, WaterSensor> pattern = Pattern.<WaterSensor>begin("s1")
            .where(new SimpleCondition<WaterSensor>()
            {
                //定义匹配规则
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "s1".equals(value.getId());
                }
            })
            /*
                要求当前数据必须是s1，下一条必须在2s之内(不包含2s)到达
                     s1 .... 间隔<2s.....  s3:  未超时，但是不符合模式，匹配不成功，就不会输出。
                     s1 .... 间隔<2s.....  s2:  未超时，符合模式，匹配成功，正常输出。
                     s1 .... 间隔>=2s..... sx：  s1要匹配的数据超时(简称s1超时)，超时输出s1
             */
            .within(Time.seconds(2))
            .next("s2")
            .where(new SimpleCondition<WaterSensor>()
            {
                //定义匹配规则
                @Override
                public boolean filter(WaterSensor value) throws Exception {
                    return "s2".equals(value.getId());
                }
            });


        PatternStream<WaterSensor> patternStream = CEP.pattern(ds, pattern);

        OutputTag<String> timeoutTag = new OutputTag<>("timeout", Types.STRING);

        SingleOutputStreamOperator<String> ds1 = patternStream.select(
            timeoutTag,
            new PatternTimeoutFunction<WaterSensor, String>()
            {
                @Override
                public String timeout(Map<String, List<WaterSensor>> pattern, long timeoutTimestamp) throws Exception {
                    return pattern.toString();
                }
            },
            new PatternSelectFunction<WaterSensor, String>()
            {

                //获取正常匹配的
                @Override
                public String select(Map<String, List<WaterSensor>> map) throws Exception {
                    return map.toString();
                }
            });

        //主流输出正常匹配
        ds1.print().setParallelism(1);
        ds1.getSideOutput(timeoutTag).printToErr();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
